#!/usr/bin/env python3
"""
攻击行为统计日志模块
专门用于记录和分析攻击行为的结构化日志
"""
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional

# 攻击行为类型枚举
class AttackType:
    AUTH_ATTEMPT = "auth_attempt"          # 认证尝试
    COMMAND_EXEC = "command_execution"     # 命令执行
    FILE_ACCESS = "file_access"           # 文件访问
    PORT_SCAN = "port_scan"               # 端口扫描
    EXPLOIT_ATTEMPT = "exploit_attempt"   # 漏洞利用尝试
    DATA_EXFILTRATION = "data_exfiltration" # 数据泄露
    RECONNAISSANCE = "reconnaissance"     # 侦察行为
    BRUTE_FORCE = "brute_force"           # 暴力破解

# 协议类型枚举
class ProtocolType:
    TCP = "tcp"
    HTTP = "http"
    HTTPS = "https"
    SSH = "ssh"
    TELNET = "telnet"
    FTP = "ftp"

class AttackLogger:
    """
    攻击行为日志记录器
    用于记录结构化的攻击行为数据，便于后续分析和统计
    """

    def __init__(self, log_file: str = "logs/attacks.jsonl"):
        """
        初始化攻击日志记录器

        Args:
            log_file (str): 攻击日志文件路径（JSONL格式）
        """
        self.log_file = Path(log_file)
        self.log_file.parent.mkdir(parents=True, exist_ok=True)

        # 创建专用的日志记录器
        self.logger = logging.getLogger("honeypot_attacks")
        self.logger.setLevel(logging.INFO)

        # 避免重复添加处理器
        if not self.logger.handlers:
            handler = logging.FileHandler(self.log_file, encoding='utf-8')
            handler.setLevel(logging.INFO)
            formatter = logging.Formatter('%(message)s')  # JSONL格式只需要消息内容
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)

    def log_attack(self,
                   timestamp: str,
                   source_ip: str,
                   destination_port: int,
                   protocol: str,
                   attack_type: str,
                   content: Dict[str, Any],
                   additional_info: Optional[Dict[str, Any]] = None):
        """
        记录攻击行为

        Args:
            timestamp (str): 时间戳（ISO格式）
            source_ip (str): 攻击源IP地址
            destination_port (int): 目标端口
            protocol (str): 协议类型
            attack_type (str): 攻击行为类型
            content (dict): 攻击内容（如命令、认证凭据等）
            additional_info (dict, optional): 其他附加信息
        """
        # 构建结构化日志条目
        log_entry = {
            "timestamp": timestamp,
            "source_ip": source_ip,
            "destination_port": destination_port,
            "protocol": protocol,
            "attack_type": attack_type,
            "content": content,
            "additional_info": additional_info or {}
        }

        # 写入JSONL格式的日志文件
        try:
            log_line = json.dumps(log_entry, ensure_ascii=False)
            self.logger.info(log_line)
        except Exception as e:
            # 如果JSON序列化失败，记录错误
            error_entry = {
                "timestamp": datetime.now().isoformat(),
                "source_ip": source_ip,
                "destination_port": destination_port,
                "protocol": protocol,
                "attack_type": "logging_error",
                "content": {"error": str(e)},
                "additional_info": {"original_content": str(content)}
            }
            error_line = json.dumps(error_entry, ensure_ascii=False)
            self.logger.info(error_line)

    def log_auth_attempt(self,
                        source_ip: str,
                        destination_port: int,
                        protocol: str,
                        username: str,
                        password: str = None,
                        pubkey_fingerprint: str = None,
                        success: bool = False):
        """
        记录认证尝试

        Args:
            source_ip (str): 攻击源IP
            destination_port (int): 目标端口
            protocol (str): 协议类型
            username (str): 用户名
            password (str, optional): 密码
            pubkey_fingerprint (str, optional): 公钥指纹
            success (bool): 认证是否成功
        """
        content = {
            "username": username,
            "password": password,
            "pubkey_fingerprint": pubkey_fingerprint,
            "success": success
        }

        self.log_attack(
            timestamp=datetime.now().isoformat(),
            source_ip=source_ip,
            destination_port=destination_port,
            protocol=protocol,
            attack_type=AttackType.AUTH_ATTEMPT,
            content=content
        )

    def log_command_execution(self,
                            source_ip: str,
                            destination_port: int,
                            protocol: str,
                            command: str,
                            command_type: str = "unknown"):
        """
        记录命令执行

        Args:
            source_ip (str): 攻击源IP
            destination_port (int): 目标端口
            protocol (str): 协议类型
            command (str): 执行的命令
            command_type (str): 命令类型（如shell命令、SQL命令等）
        """
        content = {
            "command": command,
            "command_type": command_type
        }

        self.log_attack(
            timestamp=datetime.now().isoformat(),
            source_ip=source_ip,
            destination_port=destination_port,
            protocol=protocol,
            attack_type=AttackType.COMMAND_EXEC,
            content=content
        )

    def log_file_access(self,
                       source_ip: str,
                       destination_port: int,
                       protocol: str,
                       file_path: str,
                       access_type: str = "read"):
        """
        记录文件访问

        Args:
            source_ip (str): 攻击源IP
            destination_port (int): 目标端口
            protocol (str): 协议类型
            file_path (str): 文件路径
            access_type (str): 访问类型（read/write/delete等）
        """
        content = {
            "file_path": file_path,
            "access_type": access_type
        }

        self.log_attack(
            timestamp=datetime.now().isoformat(),
            source_ip=source_ip,
            destination_port=destination_port,
            protocol=protocol,
            attack_type=AttackType.FILE_ACCESS,
            content=content
        )

    def log_port_scan(self,
                     source_ip: str,
                     destination_port: int,
                     protocol: str,
                     scan_type: str):
        """
        记录端口扫描

        Args:
            source_ip (str): 攻击源IP
            destination_port (int): 目标端口
            protocol (str): 协议类型
            scan_type (str): 扫描类型（如SYN扫描、TCP连接扫描等）
        """
        content = {
            "scan_type": scan_type
        }

        self.log_attack(
            timestamp=datetime.now().isoformat(),
            source_ip=source_ip,
            destination_port=destination_port,
            protocol=protocol,
            attack_type=AttackType.PORT_SCAN,
            content=content
        )

# 创建全局攻击日志记录器实例
attack_logger = AttackLogger()

__all__ = ["attack_logger", "AttackType", "ProtocolType", "AttackLogger"]
